'use strict';

var _ = require('lodash');
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var wiredep = require('wiredep').stream;
var gulpSequence = require('gulp-sequence');
var browserSync = require('./browserSync');

/**
 * 读取gulp相关插件
 */
var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});

/**
 * 文件汇总
 */
gulp.task('main', function() {
  var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), {
    read: false
  });
  var partialsInjectOptions = {
    starttag: '<!-- inject:partials -->',
    ignorePath: conf.paths.tmp,
    addRootSlash: false
  };

  var htmlFilter = $.filter('*.html', {
    restore: true
  });
  var jsFilter = $.filter('**/*.js', {
    restore: true
  });
  var cssFilter = $.filter('**/*.css', {
    restore: true
  });

  return gulp.src(path.join(conf.paths.tmp, '/index.html'))
    .pipe($.inject(partialsInjectFile, partialsInjectOptions)) /// 注入inject标签内partials文件路径
    .pipe($.useref()) /// 合并build标签内的文件
    .pipe($.rev()) /// 文件名加随机字符串
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    // .pipe($.uglify({
    //   preserveComments: $.uglifySaveLicense
    // }))
    .on('error', console.error)
    .pipe(jsFilter.restore)
    .pipe(cssFilter)
    // .pipe($.csso())
    .pipe(cssFilter.restore)
    .pipe($.revReplace())
    .pipe(htmlFilter)
    .pipe($.minifyHtml({ /// 压缩html文件
      empty: true,
      spare: true,
      quotes: true,
      conditionals: true
    }))
    .pipe($.rename('index.html'))
    .pipe(htmlFilter.restore)
    .pipe(gulp.dest(conf.paths.dist))
    .pipe($.size({
      title: conf.paths.dist,
      showFiles: true
    }))
    .pipe(browserSync.reload({stream: true}));
});

/**
 * html文件缓存到js文件中
 */
gulp.task('html', function() {
  return gulp.src([
      path.join(conf.paths.src, '/scripts/**/*.html')
    ])
    .pipe($.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe($.angularTemplatecache('templateCacheHtml.js', {
      module: 'proxyMirrorApp',
      root: 'scripts'
    }))
    .pipe(gulp.dest(conf.paths.tmp + '/partials/'));
});

/**
 * 编译less文件为css文件
 * 合并, 压缩css文件
 * 输出到临时文件夹
 */
gulp.task('styles', function() {
  return gulp.src([
      path.join(conf.paths.src, '/styles/**/app.less')
    ])
    .pipe($.less({ // 编译less为css
      // compress: true // 压缩css
    }))
    .on('error', function(e) {
      console.error(e);
    })
    .pipe($.concat('all.css')) // 合并css
    // .pipe($.csso()) // 压缩css
    .pipe(gulp.dest(path.join(conf.paths.tmp, '/styles/')))
    .pipe($.size({
      title: path.join(conf.paths.tmp, '/styles/'),
      showFiles: true
    }));
});

/**
 * 合并,压缩js文件
 * 输出到临时文件夹
 */
gulp.task('scripts', function() {
  return gulp.src([
      path.join(conf.paths.src, '/scripts/**/*.js')
    ])
    .pipe($.concat('all.js')) // 合并js
    // .pipe($.uglify({ // 压缩js
    //   preserveComments: $.uglifySaveLicense
    // }))
    .on('error', function(e) {
      console.error(e);
    })
    .pipe(gulp.dest(conf.paths.tmp + '/scripts/'))
    .pipe($.size({
      title: path.join(conf.paths.tmp, '/scripts/'),
      showFiles: true
    }));
});

/**
 * 往index.html中实现注入依赖的css|js文件路径
 */
gulp.task('inject', function() {
  var injectStyles = gulp.src([
    path.join(conf.paths.tmp, 'styles/**/*.css')
  ]);
  var injectScripts = gulp.src([
    path.join(conf.paths.tmp, 'scripts/**/*.js')
  ]);
  var injectOptions = {
    ignorePath: [conf.paths.src, conf.paths.tmp],
    addRootSlash: false
  };
  return gulp.src(path.join(conf.paths.src, '/index.html'))
    .pipe($.inject(injectStyles, injectOptions))
    .pipe($.inject(injectScripts, injectOptions))
    .pipe(wiredep(_.extend({}, conf.wiredep)))
    .pipe(gulp.dest(path.join(conf.paths.tmp, '/')));
});

/**
 * 直接移动其他文件
 */
gulp.task('other', function() {
  var fileFilter = $.filter(function(file) {
    return file.stat.isFile();
  });

  return gulp.src([
      path.join(conf.paths.src, '/404.html'),
      path.join(conf.paths.src, '/**/*.{ico,jpg,png}')
    ])
    .pipe(fileFilter)
    .pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});

/**
 * 测试静态文件
 */
gulp.task('test:task', function() {
  return gulp.src([
      path.join(conf.paths.src, '/404.html')
    ])
    .pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});

/**
 * 清理临时文件夹和目标文件夹
 */
gulp.task('clean', function(done) {
  return $.del([conf.paths.dist, conf.paths.tmp], done);
});

/**
 * 设置任务队列
 */
gulp.task('build', gulpSequence(['styles', 'scripts', 'html', 'other'], 'inject', 'main'));
